<template>
  <view class="practice">
    <view class="title">
      <view>{{ bookName }}</view>
      <text>{{ chapterName }}</text>
    </view>
    <view class="content">
      <view class="box" v-show="!isShowResult">
        <view class="sentence">
          <text class="active">{{ sentenceEnglish }}</text>
          <text>{{ sentenceChinese }}</text>
        </view>
        <view class="shape" :class="{ active: isRecording }">
          <RecordShape></RecordShape>
        </view>
        <view class="button">
          <view class="button_content" v-if="!isPlaying">
            <view
              class="button_img"
              :class="{ disabled: isRecording }"
              @click="play()"
            >
              <image
                src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/common/yinliang.png"
                alt=""
                mode="widthFix"
              ></image>
            </view>
            <view class="button_text">播放</view>
          </view>
          <view class="button_content" v-else>
            <view class="button_img" @click="suspend()">
              <image
                src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/common/yinliang.png"
                alt=""
                mode="widthFix"
              ></image>
            </view>
            <view class="button_text">暂停</view>
          </view>
          <view class="button_content" v-if="!isRecording">
            <view class="button_img" @click="record()">
              <image
                src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/common/yinliang.png"
                alt=""
                mode="widthFix"
              ></image>
            </view>
            <view class="button_text">录音</view>
          </view>
          <view class="button_content" v-else>
            <view class="button_img button_recording" @click="endRecord()">
              <view class="button_img_con">
                <image
                  src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/common/yinliang.png"
                  alt=""
                  mode="widthFix"
                ></image>
              </view>
            </view>
            <view class="button_text">结束录音</view>
            <view class="button_text button_text_time">
              {{ countText }}
            </view>
          </view>
          <view class="button_content">
            <view
              class="button_img"
              :class="{ disabled: !isCanListen }"
              @click="playVoice()"
            >
              <image
                src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/common/yinliang.png"
                alt=""
                mode="widthFix"
              ></image>
            </view>
            <view class="button_text">收听</view>
          </view>
          <view class="button_content">
            <view
              class="button_img"
              :class="{
                disabled: !isCanNext || endFlag,
              }"
              @click="nextSentence()"
            >
              <image
                src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/common/yinliang.png"
                alt=""
                mode="widthFix"
              ></image>
            </view>
            <view class="button_text">下一句</view>
          </view>
        </view>
      </view>
      <view class="box" v-show="isShowResult">
        <view class="sentence">
          <text class="active">{{ sentenceEnglish }}</text>
          <text>{{ sentenceChinese }}</text>
        </view>
        <view class="info">
          <view class="info_button">
            <view class="button_content" v-if="!isPlaying">
              <view class="button_img" @click="play()">
                <image
                  src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/common/yinliang.png"
                  alt=""
                  mode="widthFix"
                ></image>
              </view>
              <view class="button_text">播放</view>
            </view>
            <view class="button_content" v-else>
              <view class="button_img" @click="suspend()">
                <image
                  src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/common/yinliang.png"
                  alt=""
                  mode="widthFix"
                ></image>
              </view>
              <view class="button_text">暂停</view>
            </view>
            <view class="button_content">
              <view class="button_img" @click="record()">
                <image
                  src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/common/yinliang.png"
                  alt=""
                  mode="widthFix"
                ></image>
              </view>
              <view class="button_text">录音</view>
            </view>
          </view>
          <view class="shape active">
            <view class="charts_box">
              <qiun-data-charts
                type="radar"
                :chartData="chartData"
                background="none"
              />
            </view>
          </view>
          <view class="info_button active">
            <view class="button_content">
              <view
                class="button_img"
                :class="{ disabled: !isCanListen }"
                @click="playVoice()"
              >
                <image
                  src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/common/yinliang.png"
                  alt=""
                  mode="widthFix"
                ></image>
              </view>
              <view class="button_text">收听</view>
            </view>
            <view class="button_content">
              <view
                class="button_img"
                :class="{
                  disabled: !isCanNext || endFlag,
                }"
                @click="nextSentence()"
              >
                <image
                  src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/common/yinliang.png"
                  alt=""
                  mode="widthFix"
                ></image>
              </view>
              <view class="button_text">下一句</view>
            </view>
          </view>
        </view>
        <view class="result">
          <view
            class="result_container"
            :class="{ active: total_score >= passScore && isShowTips }"
            v-show="total_score >= passScore"
          >
            <view class="result_image">
              <image
                src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/laugh.png"
                alt=""
                mode="widthFix"
              ></image>
            </view>
            <view class="result_content">
              <view class="result_text">
                <text>恭喜你！已通过。</text>
              </view>
              <view class="result_text" v-if="nonStandardList.length > 0">
                <text>你需要提升的有:</text>
                <view
                  class=""
                  v-for="(item, index) in nonStandardList"
                  :key="index"
                >
                  <text class="active" v-html="item"></text>
                </view>
              </view>
            </view>
          </view>
          <view
            class="result_container"
            :class="{ active: total_score < passScore && isShowTips }"
            v-show="total_score < passScore"
          >
            <view class="result_image">
              <image
                src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/cry.png"
                alt=""
                mode="widthFix"
              ></image>
            </view>
            <view class="result_content">
              <view class="result_text">
                <text>很遗憾！未通过。</text>
              </view>
              <view class="result_text" v-if="nonStandardList.length > 0">
                <text>你需要提升的有:</text>
                <text
                  class="active"
                  v-for="(item, index) in nonStandardList"
                  :key="index"
                  v-html="item"
                ></text>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="progress">
        <view class="progress_container">
          <view
            class="progress_content"
            :style="{ width: currentWidth + '%' }"
          ></view>
        </view>
        <view class="progress_text">
          <text>第{{ sentenceSort + 1 }}题</text>
          <text>共{{ sentenceNum }}题</text>
        </view>
      </view>
    </view>
    <Tips :show="showTips" :content="tipsContent"></Tips>
  </view>
</template>

<script>
import { getRandom, getRandomToDecimal } from "@/libs/tools";
import permision from "@/js_sdk/wa-permission/permission.js";
import parser from "fast-xml-parser";

const recorderManager = uni.getRecorderManager();
const innerAudioContext = uni.createInnerAudioContext();

innerAudioContext.autoplay = true;
export default {
  components: {},
  props: {
    bookName: {
      type: String,
      default: "",
    },
    chapterName: {
      type: String,
      default: "",
    },
    sentence: {
      type: Object,
      default: null,
    },
    sentenceSort: {
      type: Number,
      default: 0,
    },
    sentenceNum: {
      type: Number,
      default: 0,
    },
  },
  computed: {
    currentWidth() {
      return parseInt(((this.sentenceSort + 1) / this.sentenceNum) * 100);
    },
  },
  filters: {
    numberFilter(num) {
      const keys = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
      var bit,
        ten,
        hundredth,
        thousand,
        str = "";
      thousand = parseInt(num / 1000);
      num %= 1000;
      hundredth = parseInt(num / 100);
      num %= 100;
      ten = parseInt(num / 10);
      num %= 10;
      bit = parseInt(num);
      if (thousand) {
        str = str.concat(keys[thousand], "千");
      }
      if (hundredth) {
        str = str.concat(keys[hundredth], "百");
      } else if (thousand) {
        str = str.concat("零");
      }
      if (ten) {
        str = str.concat(keys[ten], "十");
      } else if (hundredth) {
        str = str.concat("零");
      }
      if (bit) {
        str = str.concat(keys[bit]);
      } else if (!ten) {
        str = str.slice(0, -1);
      }
      return str;
    },
  },
  created() {
    // #ifdef APP-PLUS
    this.isIos = plus.os.name == "iOS";
    // #endif
    let self = this;
    recorderManager.onStop(function (res) {
      self.voicePath = res.tempFilePath;
      self.uploadVoice();
    });
    this.initData();
  },
  data() {
    return {
      isIos: true,
      voicePath: "",
      recordOptions: {
        duration: 60000,
        sampleRate: 16000,
        encodeBitRate: 48000,
      },
      permisionIosMap: {
        location: "位置",
        camera: "摄像头",
        photoLibrary: "相册",
        record: "麦克风",
        push: "推送",
        contact: "通讯录",
        calendar: "日历",
        memo: "备忘录",
      },
      permisionAndroidMap: {
        "android.permission.ACCESS_FINE_LOCATION": "位置",
        "android.permission.ACCESS_COARSE_LOCATION": "模糊位置",
        "android.permission.CAMERA": "摄像头",
        "android.permission.READ_EXTERNAL_STORAGE": "外部存储(含相册)读取",
        "android.permission.WRITE_EXTERNAL_STORAGE": "外部存储(含相册)写入",
        "android.permission.RECORD_AUDIO": "麦克风",
        "android.permission.READ_CONTACTS": "通讯录读取",
        "android.permission.WRITE_CONTACTS": "通讯录写入",
        "android.permission.READ_CALENDAR": "日历读取",
        "android.permission.WRITE_CALENDAR": "日历写入",
        "android.permission.READ_SMS": "短信读取",
        "android.permission.SEND_SMS": "短信发送",
        "android.permission.RECEIVE_SMS": "接收新短信",
        "android.permission.READ_PHONE_STATE": "获取手机识别码等信息的",
        "android.permission.CALL_PHONE": "拨打电话",
        "android.permission.READ_CALL_LOG": "获取通话记录",
      },
      sentenceEnglish: "",
      sentenceChinese: "",
      audio: null,
      isPlaying: false,
      isSuspend: false,
      isRecording: false,
      isCanListen: false,
      isCanNext: false,
      endFlag: false,
      recorderCount: 0,
      passCount: 3,
      senconds: 0,
      countText: "",
      countInterval: null,
      isShowResult: false,
      isShowTips: false,
      isCanClick: true,
      passScore: 80,
      isPass: false,
      accuracy_score: 0, //准确度评分
      fluency_score: 0, //流畅度评分
      integrity_score: 0, //完整度评分
      standard_score: 0, //标准度评分
      total_score: 0, //篇章总分
      nonStandardList: [],
      sentenceResult: "",
      chartData: {},
      showTips: false,
      tipsContent: "已连续三次未通过",
    };
  },
  methods: {
    initData() {
      this.sentenceEnglish = this.sentence.sentence;
      this.sentenceChinese = this.sentence.chinese;
    },
    initSentence() {
      this.isShowResult = false;
      this.isShowTips = false;
      this.isCanListen = false;
      this.isCanNext = false;
      this.senconds = 0;
      this.nonStandardList = [];
      this.sentenceResult = "";
      this.chartData = {};
    },
    play() {
      if (this.isRecording) return;
      if (!this.isSuspend) {
        this.audio = uni.createInnerAudioContext();
        this.audio.src = this.sentence.audio;
        this.audio.play();
        this.audio.onEnded(() => {
          this.isPlaying = false;
          this.isSuspend = false;
        });
        this.audio.onError(() => {
          this.isPlaying = false;
          this.isSuspend = false;
        });
        this.isPlaying = true;
      } else {
        this.audio.play();
        this.isPlaying = true;
      }
    },
    suspend() {
      this.isPlaying = false;
      this.isSuspend = true;
      this.audio.pause();
    },
    record() {
      if (!this.isCanClick) return;
      this.isCanClick = false;
      setTimeout(() => {
        this.isCanClick = true;
      }, 1000);
      if (this.isShowResult) {
        this.initSentence();
      }
      if (this.isIos) {
        this.judgeIosPermission("record");
      } else {
        this.requestAndroidPermission("android.permission.RECORD_AUDIO");
      }
    },
    judgeIosPermission: function (permisionID) {
      var result = permision.judgeIosPermission(permisionID);
      var strStatus = result ? "已" : "未";
      if (!result) {
        uni.showModal({
          title: "",
          content:
            this.permisionIosMap[permisionID] +
            "权限" +
            strStatus +
            "获得授权,是否去开启？",
          showCancel: false,
          success: (res) => {
            if (res.confirm) {
              plus.runtime.openURL("app-settings://");
            }
          },
        });
      } else {
        this.startRecord();
      }
    },
    async requestAndroidPermission(permisionID) {
      var result = await permision.requestAndroidPermission(permisionID);
      var strStatus;
      if (result == 1) {
        strStatus = "已获得授权";
        this.startRecord();
      } else if (result == 0) {
        strStatus = "未获得授权";
      } else {
        strStatus = "被永久拒绝权限";
        uni.showModal({
          title: "",
          content: this.permisionAndroidMap[permisionID] + "权限" + strStatus,
          showCancel: false,
        });
      }
    },
    startRecord() {
      recorderManager.start(this.recordOptions);
      this.isRecording = true;
      this.countText = "00:00";
      this.countInterval = setInterval(() => {
        this.senconds++;
        let second = this.senconds - Math.floor(this.senconds / 60) * 60;
        second < 10 ? (second = "0" + second) : "";
        this.countText = "0" + Math.floor(this.senconds / 60) + ": " + second;
        if (this.senconds >= 60) {
          this.isRecording = false;
          this.endRecord();
          clearInterval(this.countInterval);
        }
      }, 1000);
    },
    endRecord() {
      recorderManager.stop();
      clearInterval(this.countInterval);
      this.second = 0;
      this.minute = 0;
      this.isRecording = false;
      this.isShowResult = true;
    },
    playVoice() {
      if (!this.isCanListen) return;
      if (this.voicePath) {
        innerAudioContext.src = this.voicePath;
        innerAudioContext.play();
      }
    },
    uploadVoice() {
      this.$upload(this.voicePath, { wordText: this.sentenceEnglish }).then(
        (res) => {
          let xml = res.data;
          let grade = parser.parse(xml, {
            attributeNamePrefix: "",
            ignoreAttributes: false,
          });
          if (grade) {
            let read_chapter =
              grade.xml_result.read_sentence.rec_paper.read_chapter;
            this.accuracy_score = parseInt(read_chapter.accuracy_score);
            this.fluency_score = parseInt(read_chapter.fluency_score);
            this.integrity_score = parseInt(read_chapter.integrity_score);
            this.standard_score = parseInt(read_chapter.standard_score);
            this.total_score = parseInt(read_chapter.total_score);
            this.isPass = this.total_score >= this.passScore ? true : false;

            if (this.isPass) {
              this.isCanNext = true;
            } else {
              this.recorderCount++;
              if (this.recorderCount >= this.passCount) {
                this.isCanNext = true;
                if (this.recorderCount === this.passCount) {
                  this.showTips = true;
                  setTimeout(() => {
                    this.showTips = false;
                  }, 2000);
                }
                this.isCanNext = true;
                this.isPass = true;
                let start = this.passScore;
                let end = 100;
                this.total_score = getRandomToDecimal(start, end);
              }
            }
            this.isCanListen = true;
            this.isShowTips = true;
            this.initEcharts();
            this.initNonStandard(read_chapter);
            this.saveRecord();
          }
        }
      );
    },
    initEcharts() {
      this.chartData = {
        categories: [
          "总分" + this.total_score + "分",
          "准确度" + this.accuracy_score + "分",
          "流畅度" + this.fluency_score + "分",
          "完整度" + this.integrity_score + "分",
          "标准度" + this.standard_score + "分",
        ],
        series: [
          {
            name: "评分",
            data: [
              this.total_score,
              this.accuracy_score,
              this.fluency_score,
              this.integrity_score,
              this.standard_score,
            ],
          },
        ],
      };
    },
    initNonStandard(read_chapter) {
      let sentence = read_chapter.sentence;
      let anArray = [];
      if (!Array.isArray(sentence)) {
        anArray.push(sentence);
      } else {
        anArray = sentence;
      }
      anArray.forEach((item) => {
        let anWordArray = [];
        if (!Array.isArray(item.word)) {
          anWordArray.push(item.word);
        } else {
          anWordArray = item.word;
        }
        anWordArray.forEach((item) => {
          if (item.dp_message === "32") return;
          if (item.content !== "sil" && item.content !== "fil") {
            if (item.total_score < 60) {
              this.nonStandardList.push(item.content);
              this.sentenceResult += `<em>${item.content}</em>\t`;
            } else {
              this.sentenceResult += item.content + "\t";
            }
          }
        });
      });
    },
    nextSentence() {
      if (!this.isCanNext || this.endFlag) return;
      this.recorderCount = 0;
      this.initSentence();
      this.$emit("change");
    },
    saveRecord() {
      this.$emit("save", this.isPass, this.total_score, this.nonStandardList);
    },
    handleSaveData(endFlag) {
      this.endFlag = endFlag;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./SpokenPractice.scss";
</style>
